#!/bin/bash

# 颜色定义
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
CYAN='\033[1;36m'
NC='\033[0m'

# 生成唯一规则名
generate_rule_name() {
    echo "rule_$(date +%s)_${RANDOM:0:3}"
}

# 错误处理
die() {
    echo -e "${RED}[ERR] $1${NC}" >&2
    exit 1
}

# 检测系统类型
detect_system() {
    if [ -f /etc/synoinfo.conf ] && [ -d /var/packages ]; then
        echo "dsm"
    elif grep -q "ID=debian" /etc/os-release && ls /vol1* &>/dev/null; then
        echo "fnos"
    else
        echo "linux"
    fi
}

# 获取配置文件路径
get_config_path() {
    local config_path
    case $(detect_system) in
        "dsm")   
            config_path=$(find /volume* -maxdepth 2 -path "*/docker/frp/frpc.yml" 2>/dev/null | head -n1)
            [ -z "$config_path" ] && config_path="/volume1/docker/frp/frpc.yml"
            ;;
        "fnos") 
            config_path=$(find /vol* -maxdepth 3 -path "*/1000/docker/frp/frpc.yml" 2>/dev/null | head -n1)
            [ -z "$config_path" ] && config_path="/vol1/1000/docker/frp/frpc.yml"
            ;;
        *)       
            config_path="/opt/docker/frp/frpc.yml"
            ;;
    esac
    
    # 如果文件不存在则创建
    if [ ! -f "$config_path" ]; then
        mkdir -p "$(dirname "$config_path")"
        touch "$config_path"
        echo "[common]" >> "$config_path"
        echo "server_addr = your_server_address" >> "$config_path"
        echo "server_port = 7000" >> "$config_path"
        echo "token = your_token" >> "$config_path"
    fi
    
    echo "$config_path"
}

# 验证端口
validate_port() {
    [[ "$1" =~ ^[0-9]+$ ]] && [ "$1" -ge 1 -a "$1" -le 65535 ]
}

# 检查端口冲突
check_port_used() {
    grep -q "remote_port = $1" "$2"
}

# 显示规则表格
show_rules() {
    local file="$1"
    echo -e "\n${CYAN}====== 当前转发规则 ======${NC}"
    
    if [ ! -s "$file" ]; then
        echo "（暂无规则）"
        return
    fi
    
    # 使用awk实现基本表格对齐
    awk -F'[ =]+' '
        BEGIN {
            printf "%-20s %-8s %-15s %-10s %-10s\n", 
            "规则名称", "类型", "本地IP", "本地端口", "远程端口"
            printf "%-20s %-8s %-15s %-10s %-10s\n", 
            "--------------------", "--------", "---------------", "----------", "----------"
        }
        /^\[/ && !/common/ { 
            gsub(/\[|\]/, ""); 
            name=$0 
            getline type_line; split(type_line, type_arr, " = ")
            getline ip_line; split(ip_line, ip_arr, " = ")
            getline lport_line; split(lport_line, lport_arr, " = ")
            getline rport_line; split(rport_line, rport_arr, " = ")
            
            printf "%-20s %-8s %-15s %-10s %-10s\n", 
            name, type_arr[2], ip_arr[2], lport_arr[2], rport_arr[2]
        }
    ' "$file"
    echo
}

# 添加规则
add_rule() {
    local file="$1"
    local name=$(generate_rule_name)
    
    echo -e "${GREEN}>>> 添加新规则${NC}"
    read -p "规则名称 (默认 ${name}): " input_name
    name=${input_name:-$name}

    # 检查名称冲突
    while grep -q "\[$name\]" "$file"; do
        echo -e "${RED}规则名称已存在！${NC}"
        read -p "请重新输入: " name
    done

    # 输入配置
    read -p "本地IP (默认 127.0.0.1): " ip
    ip=${ip:-"127.0.0.1"}

    while true; do
        read -p "本地端口: " lport
        validate_port "$lport" && break
        echo -e "${RED}端口必须是1-65535的数字${NC}"
    done

    while true; do
        read -p "远程端口: " rport
        if ! validate_port "$rport"; then
            echo -e "${RED}无效端口号${NC}"
        elif check_port_used "$rport" "$file"; then
            echo -e "${YELLOW}该远程端口已被使用！${NC}"
            read -p "强制使用？[y/N]: " force && [[ "$force" =~ ^[yY] ]] && break
        else
            break
        fi
    done

    # 写入配置
    echo -e "\n[$name]\ntype = tcp\nlocal_ip = $ip\nlocal_port = $lport\nremote_port = $rport" >> "$file"
    echo -e "${GREEN}✔ 已添加规则: ${name}${NC}"
}

# 批量添加
batch_add() {
    local file="$1"
    while true; do
        add_rule "$file"
        read -p "继续添加？[Y/n]: " choice
        [[ "$choice" =~ ^[nN] ]] && break
    done
}

# 删除规则
delete_rule() {
    local file="$1"
    show_rules "$file"
    
    read -p "输入要删除的规则名称: " name
    if ! grep -q "\[$name\]" "$file"; then
        die "未找到规则: $name"
    fi

    # 使用sed删除规则块
    sed -i "/^\[$name\]/,/^$/d" "$file"
    echo -e "${GREEN}✔ 已删除规则: ${name}${NC}"
}

# 重启服务
restart_service() {
    echo -e "${YELLOW}重启FRPC容器...${NC}"
    if docker restart frpc >/dev/null; then
        echo -e "${GREEN}✔ 服务重启成功${NC}"
    else
        die "服务重启失败！请运行: docker logs frpc"
    fi
}

# 主菜单
main_menu() {
    clear
    local config_file=$(get_config_path)
    
    # 确保配置文件存在
    [ ! -f "$config_file" ] && die "配置文件 $config_file 不存在且创建失败"
    
    while true; do
        echo -e "${CYAN}====== FRPC规则管理 ======${NC}"
        echo -e "配置文件: ${BLUE}${config_file}${NC}"
        echo -e "${GREEN}1. 查看所有规则"
        echo -e "2. 添加单条规则"
        echo -e "3. 批量添加规则"
        echo -e "4. 删除规则"
        echo -e "5. 重启FRPC服务"
        echo -e "0. 退出${NC}"
        echo "------------------------"

        read -p "请选择操作 [0-5]: " choice
        case $choice in
            1) show_rules "$config_file" ;;
            2) add_rule "$config_file" ;;
            3) batch_add "$config_file" ;;
            4) delete_rule "$config_file" ;;
            5) restart_service ;;
            0) exit 0 ;;
            *) echo -e "${RED}无效选择！${NC}" ;;
        esac

        read -p "按回车键继续..."
        clear
    done
}

# 初始化检查
init_check() {
    [ "$(id -u)" -ne 0 ] && die "请使用root权限运行"
    ! command -v docker &>/dev/null && die "请先安装Docker"
    ! docker inspect frpc &>/dev/null && die "FRPC容器未运行"
}

init_check
main_menu